package com.cloud.boot.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.boot.user.mapper.SysUerRoleMapper;
import com.cloud.boot.user.model.entity.SysUserRoleDO;
import com.cloud.boot.user.model.vo.RoleRefListVO;
import com.cloud.boot.user.service.SysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author lhd
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUerRoleMapper, SysUserRoleDO> implements SysUserRoleService {

    @Override
    public List<Long> getRoleIdListByUserId(Long userId) {
        if (userId == null) {
            return List.of();
        }
        return listObjs(Wrappers.<SysUserRoleDO>lambdaQuery().select(SysUserRoleDO::getRoleId).eq(SysUserRoleDO::getUserId, userId));
    }

    @Override
    public List<RoleRefListVO> getRoleListByUserId(Long userId) {
        if (userId == null) {
            return List.of();
        }
        return baseMapper.getRoleListByUserId(userId);
    }

    @Override
    public Long countUserByRoleId(Long roleId) {
        return count(Wrappers.<SysUserRoleDO>lambdaQuery().eq(SysUserRoleDO::getRoleId, roleId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveUserRole(Long userId, Set<Long> roleIdSet) {
        if (userId == null || CollUtil.isEmpty(roleIdSet)) {
            return;
        }
        List<SysUserRoleDO> doList = new ArrayList<>();
        for (Long roleId : roleIdSet) {
            SysUserRoleDO dataObj = new SysUserRoleDO();
            dataObj.setUserId(userId);
            dataObj.setRoleId(roleId);
            doList.add(dataObj);
        }

        remove(Wrappers.<SysUserRoleDO>lambdaQuery().eq(SysUserRoleDO::getUserId, userId));
        saveBatch(doList);
    }


}
